package lcr;

import java.util.ArrayList;
import java.util.Arrays;

public class Test0074 {
}

class Solution0074_1 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (x, y) -> x[0]-y[0]==0?x[1]-y[1]:x[0]-y[0]);

        int len = intervals.length;
        if (len == 0) return new int[0][2];
        ArrayList<int[]> list = new ArrayList<>();

        int[] cur = intervals[0];
        list.add(cur);
        for (int i = 1; i < len; i++) {
            int[] nums = intervals[i];
            if (nums[0] <= cur[1]){
                cur[1] = Math.max(cur[1], nums[1]);
            }
            else {
                list.add(nums);
                cur = nums;
            }
        }

        return list.toArray(new int[list.size()][]);
    }
}
